package com.yonyou.wdt.job;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.DateUtils;
import com.yonyou.wdt.utils.RedisUtils;
import com.yonyou.wdt.utils.WdtClient;
import com.yonyou.wdt.utils.WdtConfigProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName YsProductToRedisJob
 * @Description YS物料档案信息同步Redis
 * @Author HuangWb
 * @Date 2023/5/12 18:35
 * @Version 1.0
 */
@Component
public class YsProductToWdtJob extends BaseConfig {


    private static Logger logger = LoggerFactory.getLogger(YsProductToWdtJob.class);
    private final WdtConfigProperties configProperties;
    @Autowired
    public YsProductToWdtJob(WdtConfigProperties configProperties) {
        this.configProperties = configProperties;
    }
    @Resource
    private YonsuiteService yonsuiteService;

    private static final String JOB_CLASS="maoEr012";
    @XxlJob("YsProductToWdtJob")
    public ReturnT<String> YsProductToWdtJob(String params) throws Exception {
        String param = XxlJobHelper.getJobParam();
        Map<String, Object> wlParam = new HashMap<>();
        if (param != null && !"".equals(param)) {
            List<String> timeRange = Arrays.asList(param.split("\\|"));
            if (timeRange.size() == 2) {
                wlParam.put("beganTime", timeRange.get(0));
                wlParam.put("endTime", timeRange.get(1));
            } else {
                wlParam.put("productCode", timeRange.get(0));
            }
        } else {
            // 默认查询前一天的数据
            wlParam.put("beganTime", DateUtils.getStartDateBy10m());
            wlParam.put("endTime", DateUtils.getEndDateBy10m());
        }
        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(JOB_CLASS, dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        wlParam.put("pageIndex", 1);
        wlParam.put("pageSize", 100);
        boolean isNext = true;
        List<JSONObject> list = new ArrayList();
        int error = 0;
        int pageIndex = 1;
        while (true) {
            wlParam.put("pageIndex", pageIndex);
            JSONObject allocationRes = yonsuiteService.ysProductQuery(wlParam, dto);
            if (allocationRes.getStr("code").equals("200")) {
                if (null != allocationRes.getJSONObject("data") && null != allocationRes.getJSONObject("data").getJSONArray("recordList")) {
                    JSONArray purJSONArray = allocationRes.getJSONObject("data").getJSONArray("recordList");
                    for (Object allocation : purJSONArray) {
                        JSONObject allocationJson = (JSONObject) allocation;
                        HashMap<String, Object> detailMap = new HashMap<>(2);
                        String proCode = allocationJson.getStr("code");
                        detailMap.put("productCode", proCode);
                        detailMap.put("orgId", allocationJson.getStr("createOrgId"));
                        JSONObject detailRes = yonsuiteService.ysProductDetailQuery(detailMap, dto);
                        if (detailRes.getStr("code").equals("200")) {
                            JSONObject proData = detailRes.getJSONObject("data");
                            JSONObject proDetails = proData.getJSONObject("detail");
                            JSONObject proDefJsonObject = proData.getJSONObject("productCharacterDef");
                            if (proDefJsonObject != null && Boolean.TRUE.equals(proDefJsonObject.getBool("maoer02"))) {
                                Map<String, Object>[] goods_list = new Map[1];
                                Map<String, Object>[] spec_list = new Map[1];

                                //JSONObject modelDescription = allocationJson.getJSONObject("name");
                                spec_list[0] = new HashMap<String, Object>();
//            spec_list[0].put("spec_no", proCode);
                                spec_list[0].put("spec_no", proDetails.getStr("barCode"));
                                spec_list[0].put("spec_name", allocationJson.getStr("name")); //规格名称
                                spec_list[0].put("barcode", proDetails.getStr("barCode")); //主条码


                                //JSONObject name = allocationJson.getJSONObject("name");
                                goods_list[0] = new HashMap<String, Object>();
                                goods_list[0].put("goods_no", proCode);
                                goods_list[0].put("goods_type", "1");
                                goods_list[0].put("goods_name", allocationJson.getStr("name"));

                                goods_list[0].put("class_name", "销售货品");

                                goods_list[0].put("unit_name", proDetails.getStr("produceUnitName"));
                                goods_list[0].put("spec_list", spec_list);

                                //通过第三方json解析工具类fastjson将map解析成json
                                String goods_list_json = JSON.toJSONString(goods_list);

                                Map<String, Object> reqParams = new HashMap<>();
                                reqParams.put("goods_list", goods_list_json);
                                WdtClient client = new WdtClient(configProperties.getSid(), configProperties.getKey(), configProperties.getSecret(), configProperties.getUrl());

                                try {
                                    String response = client.execute("goods_push.php", reqParams);
                                    JSONObject json = JSONUtil.parseObj(response);
                                    if ("0".equals(json.getStr("code"))) {
                                        logger.info("新增物料：" + proCode + "成功");
                                        InsertLogger(JOB_CLASS,proCode, "1", "新增物料：" + proCode + "同步旺店通成功");
                                    } else {
                                        logger.error("新增物料：" + proCode + "失败：" + json.getStr("message"));
                                        InsertLogger(JOB_CLASS,proCode, "1", "新增物料：" + proCode + "同步旺店通成功");
                                    }
                                    this.APICurrentLimiting("goods_push.php", 60);
                                } catch (Exception e) {
                                    logger.error("调用接口失败：" + e.getMessage());
                                }
                            }
                            this.APICurrentLimiting(OpenApiURLEnum.PRODUCT_DTL_QUERY, 59);

                            list.add(allocationJson);
                        }else {
                            break;
                        }
                    }
                }
                this.APICurrentLimiting(OpenApiURLEnum.PRODUCT_FEATURE_LIST, 59);
                if (allocationRes.getJSONObject("data").getInt("pageCount") == 0) {
                    break;
                }
                if (allocationRes.getJSONObject("data").getInt("pageCount") <= pageIndex) {
                    break;
                }
                pageIndex++;
            }
        }
            if (list.size() > 0) {
                InsertLogger(JOB_CLASS, null, "1", "租户：{" + dto.getTenantId() + "} YS系统物料档案同步wdt完成，共同步物料档案：{" + list.size() + "}条");
            }
            return ReturnT.SUCCESS;
        }
}
